<template>
  <div class="detail">
    <div class="detail-title">
      <div class="back-icon thumb" title="返回" @click="back">
        <img v-lazy="publicUrl(`/images/back.png`)" />
      </div>
      <span class="title"> 素材编辑设计 </span>
    </div>
    <div class="detail-content">
      <div class="left">
        <div class="detail-img">
          <img :src="editorImg" />
        </div>
      </div>
      <div class="right">
        <div class="canvas-container">
          <Fabric ref="fabric" @handleBlur="handleBlur" />
        </div>
        <span class="red">指定元素按下delete键可删除</span>
        <div class="tool">
          <div class="tool-part border">
            <div class="tool-part-left">海报元素</div>
            <div class="tool-part-right">
              <div class="button thumb" @click="addImg">添加图片+</div>
              <div class="button thumb" @click="addText">添加文字+</div>
            </div>
          </div>
          <div class="tool-part">
            <div class="tool-part-left border">文字颜色</div>
            <div class="color-picker">
              <ColorPicker :def-color="color" @change-color="updateColor" />
            </div>
          </div>
          <div class="tool-part">
            <div class="composite thumb" v-debounce="upload">合成下载</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="">
import { ref } from "vue";
import { publicUrl, fileToBase64Async, aDownLoad } from "@/utils/util";
import { useRouter } from "vue-router";
import Fabric from "@/components/Fabric/index.vue";
import getFile from "@/utils/getFile";
import ColorPicker from "@/components/ColorPicker/index.vue";
import { toast } from "vue3-toastify";

document.documentElement.scrollTop = 0;
const color = ref<string>("#FFAC3F");
const fabric = ref<InstanceType<typeof Fabric>>();
const router = useRouter();
const updateColor = (eventData: any) => (color.value = eventData.colors.hex);
const editorImg = ref<string>(publicUrl(`/images/poster.jpg`));

const addText = () => {
  fabric.value?.addText(color.value, `请添加文字`);
};
const handleBlur = async () => {
  let result = await fabric.value?.createImg();
  if (result) editorImg.value = result;
};
const addImg = () => {
  getFile("image", undefined, {
    errorResult: (msg: string) => toast.error(msg),
    successResult: async (file: File) => {
      let res = await fileToBase64Async(file);
      fabric.value?.addImg(res);
    },
  });
};
const upload = () => {
  aDownLoad(editorImg.value);
};

const back = async () => {
  router.go(-1);
};
</script>
<style scoped lang="scss">
@media screen and (min-width: $pc-min-width) {
  @import "./pc.scss";
}
</style>
